<?php

namespace app\controllers;

use yii;
use yii\web\Controller;
use app\models\AdminUser;
use yii\helpers\Url;
use app\lib\BaseFunction;
use Gregwar\Captcha\CaptchaBuilder;
use yii\web\Response;
use app\models\Login_log;

class LoginController extends Controller
{
    use \app\lib\Redis;

    public $layout = false;
    public $enableCsrfValidation = false;


    public function actionIndex()
    {
        return $this->render('index');
    }

    public function actionCaptcha()
    {
        $response = Yii::$app->getResponse();
        $response->headers->set('Content-Type', 'image/jpeg');
        $response->format = Response::FORMAT_RAW;
        $captcha = rand(1000, 9999);
        $builder = new CaptchaBuilder((string)$captcha);
        $builder->build();
        yii::$app->session->set('captcha', $captcha);
        $builder->output();
    }

    public function actionValidate()
    {
        $name = trim(yii::$app->request->post('name'));
        $password = trim(yii::$app->request->post('password'));
        $captcha = yii::$app->request->post("captcha");
        if ($captcha != yii::$app->session->get('captcha')) {
            echo json_encode(['status' => 0, 'msg' => '验证码错误']);
            exit;
        }
        $user = new AdminUser();
        $re = $user->login($name, md5($password));
        if ($re) {
            //添加登录记录
            //来源ip
            $login_data = [];
            $login_data['ip'] = $_SERVER['REMOTE_ADDR'];
            $login_data['time'] = time();
            $login_data['user'] = $name;
            $login_model = new Login_log();
            $login_model->insert($login_data);
            $base = new BaseFunction();
            $token = $base->generate_jwt($re['id'], $re['name']);
            $cookie = new \yii\web\Cookie(['name' => 'jwt', 'value' => $token, 'expire' => time() + 3600 * 24]);
            yii::$app->response->cookies->add($cookie);

            $msg = ['status' => 1, 'msg' => 'success', 'role' => $re['role']];
        } else {
            $msg = ['status' => 0, 'msg' => '用户名或密码错误'];
        }

        echo json_encode($msg);
    }

    /**
     *  注销登录
     */
    public function actionLogout()
    {
        yii::$app->response->cookies->remove('jwt');
        $this->redirect(Url::to(['login/index']));
    }
}
